package com.lqh.flutterModuleFirst

import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import org.json.JSONArray
import org.json.JSONObject

/**
 * Flutter通讯工具类
 * 
 * 负责处理原生Android和Flutter之间的双向通讯，包括：
 * 1. MethodChannel: 处理同步方法调用
 * 2. EventChannel: 处理异步事件流
 * 3. 数据持久化: 使用SharedPreferences存储用户数据
 * 
 * @param context Android上下文，用于访问系统资源和SharedPreferences
 * @param flutterEngine Flutter引擎实例，用于创建通讯通道
 */
class FlutterCommunicationHelper(
    private val context: Context,
    private val flutterEngine: FlutterEngine
) {
    // MethodChannel用于处理Flutter调用原生方法
    private lateinit var methodChannel: MethodChannel
    
    // EventChannel用于处理原生向Flutter发送事件
    private lateinit var eventChannel: EventChannel
    
    // EventSink用于向Flutter发送事件数据
    private lateinit var eventSink: EventChannel.EventSink
    
    // SharedPreferences用于持久化存储用户数据
    private val sharedPreferences: SharedPreferences = context.getSharedPreferences("user_data", Context.MODE_PRIVATE)

    companion object {
        // MethodChannel通道名称，必须与Flutter端保持一致
        private const val CHANNEL_NAME = "com.lqh.flutterModuleFirst/native_communication"
        
        // EventChannel通道名称，用于事件流通讯
        private const val EVENT_CHANNEL_NAME = "com.lqh.flutterModuleFirst/events"
        
        // 日志标签
        private const val TAG = "FlutterCommunicationHelper"
    }

    /**
     * 设置通讯通道
     * 
     * 初始化MethodChannel和EventChannel，建立与Flutter的通讯连接
     */
    fun setupChannels() {
        setupMethodChannel()
        setupEventChannel()
    }

    /**
     * 设置MethodChannel
     * 
     * 处理Flutter端调用的原生方法，包括：
     * - getDeviceInfo: 获取设备信息
     * - getUsers: 获取用户列表
     * - addUser: 添加用户
     * - sendDataFromFlutter: 处理Flutter发送的数据
     * - getUserById: 根据ID获取用户
     * - updateUser: 更新用户信息
     * - deleteUser: 删除用户
     */
    private fun setupMethodChannel() {
        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL_NAME)
        methodChannel.setMethodCallHandler { call, result ->
            when (call.method) {
                "getDeviceInfo" -> {
                    // 获取设备信息
                    val deviceInfo = getDeviceInfo()
                    result.success(deviceInfo)
                }
                "getUsers" -> {
                    // 获取用户列表
                    val users = getUsers()
                    result.success(users)
                }
                "addUser" -> {
                    // 添加用户
                    val userData = call.arguments as? Map<*, *>
                    val success = addUser(userData)
                    result.success(success)
                }
                "sendDataFromFlutter" -> {
                    // 处理Flutter发送的数据
                    val data = call.arguments as? String
                    handleDataFromFlutter(data)
                    result.success(null)
                }
                "getUserById" -> {
                    // 根据ID获取用户
                    val userId = call.arguments as? Int
                    val user = getUserById(userId)
                    result.success(user)
                }
                "updateUser" -> {
                    // 更新用户信息
                    val userData = call.arguments as? Map<*, *>
                    val success = updateUser(userData)
                    result.success(success)
                }
                "deleteUser" -> {
                    // 删除用户
                    val userId = call.arguments as? Int
                    val success = deleteUser(userId)
                    result.success(success)
                }
                else -> {
                    // 未实现的方法
                    result.notImplemented()
                }
            }
        }
    }

    /**
     * 设置EventChannel
     * 
     * 用于向Flutter发送事件，支持实时数据更新通知
     */
    private fun setupEventChannel() {
        try {
            eventChannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL_NAME)
            eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                    // Flutter端开始监听事件
                    eventSink = events
                    Log.d(TAG, "EventChannel listener attached")
                }

                override fun onCancel(arguments: Any?) {
                    // Flutter端取消监听事件
                    eventSink = null
                    Log.d(TAG, "EventChannel listener detached")
                }
            })
            Log.d(TAG, "EventChannel setup completed successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error setting up EventChannel", e)
        }
    }

    /**
     * 获取设备信息
     * 
     * @return 设备信息字符串，包含Android版本和设备型号
     */
    private fun getDeviceInfo(): String {
        return "Android ${android.os.Build.VERSION.RELEASE} - ${android.os.Build.MODEL}"
    }

    /**
     * 获取用户列表
     * 
     * 从SharedPreferences中读取用户数据，如果为空则返回默认用户
     * 
     * @return 用户列表，每个用户包含id、name、email、phone、createdAt字段
     */
    private fun getUsers(): List<Map<String, Any>> {
        val usersJson = sharedPreferences.getString("users", "[]")
        return try {
            val jsonArray = JSONArray(usersJson)
            val users = mutableListOf<Map<String, Any>>()
            
            // 解析JSON数组中的用户数据
            for (i in 0 until jsonArray.length()) {
                val userObj = jsonArray.getJSONObject(i)
                val user = mapOf(
                    "id" to userObj.getInt("id"),
                    "name" to userObj.getString("name"),
                    "email" to userObj.getString("email"),
                    "phone" to userObj.getString("phone"),
                    "createdAt" to userObj.getString("createdAt")
                )
                users.add(user)
            }
            
            // 如果没有用户数据，返回默认用户
            if (users.isEmpty()) {
                listOf(
                    mapOf(
                        "id" to 1,
                        "name" to "John Doe",
                        "email" to "john@example.com",
                        "phone" to "+1234567890",
                        "createdAt" to "2024-01-01T00:00:00.000Z"
                    ),
                    mapOf(
                        "id" to 2,
                        "name" to "Jane Smith",
                        "email" to "jane@example.com",
                        "phone" to "+0987654321",
                        "createdAt" to "2024-01-02T00:00:00.000Z"
                    )
                )
            } else {
                users
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error parsing users", e)
            emptyList()
        }
    }

    /**
     * 添加用户
     * 
     * 将新用户添加到用户列表中，并持久化保存
     * 
     * @param userData 用户数据，包含name、email、phone、createdAt字段
     * @return 添加是否成功
     */
    private fun addUser(userData: Map<*, *>?): Boolean {
        return try {
            Log.d(TAG, "Adding user: $userData")
            
            val users = getUsers().toMutableList()
            // 生成新的用户ID
            val newId = if (users.isNotEmpty()) users.maxOf { it["id"] as Int } + 1 else 1
            
            // 创建新用户对象
            val newUser = mapOf(
                "id" to newId,
                "name" to (userData?.get("name") ?: ""),
                "email" to (userData?.get("email") ?: ""),
                "phone" to (userData?.get("phone") ?: ""),
                "createdAt" to (userData?.get("createdAt") ?: "")
            )
            
            users.add(newUser)
            saveUsers(users)
            
            // 发送事件通知Flutter用户已更新
            sendEventToFlutter("userUpdated")
            
            true
        } catch (e: Exception) {
            Log.e(TAG, "Error adding user", e)
            false
        }
    }

    /**
     * 根据ID获取用户
     * 
     * @param userId 用户ID
     * @return 用户信息，如果不存在则返回null
     */
    private fun getUserById(userId: Int?): Map<String, Any>? {
        if (userId == null) return null
        
        val users = getUsers()
        return users.find { it["id"] == userId }
    }

    /**
     * 更新用户信息
     * 
     * @param userData 用户数据，必须包含id字段
     * @return 更新是否成功
     */
    private fun updateUser(userData: Map<*, *>?): Boolean {
        return try {
            val userId = userData?.get("id") as? Int
            if (userId == null) return false
            
            val users = getUsers().toMutableList()
            val userIndex = users.indexOfFirst { it["id"] == userId }
            
            if (userIndex != -1) {
                // 更新用户信息
                users[userIndex] = mapOf(
                    "id" to userId,
                    "name" to (userData["name"] ?: ""),
                    "email" to (userData["email"] ?: ""),
                    "phone" to (userData["phone"] ?: ""),
                    "createdAt" to (userData["createdAt"] ?: "")
                )
                
                saveUsers(users)
                sendEventToFlutter("userUpdated")
                return true
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "Error updating user", e)
            false
        }
    }

    /**
     * 删除用户
     * 
     * @param userId 要删除的用户ID
     * @return 删除是否成功
     */
    private fun deleteUser(userId: Int?): Boolean {
        return try {
            if (userId == null) return false
            
            val users = getUsers().toMutableList()
            val userIndex = users.indexOfFirst { it["id"] == userId }
            
            if (userIndex != -1) {
                users.removeAt(userIndex)
                saveUsers(users)
                sendEventToFlutter("userUpdated")
                return true
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "Error deleting user", e)
            false
        }
    }

    /**
     * 保存用户列表到SharedPreferences
     * 
     * @param users 用户列表
     */
    private fun saveUsers(users: List<Map<String, Any>>) {
        try {
            val jsonArray = JSONArray()
            users.forEach { user ->
                val userObj = JSONObject()
                userObj.put("id", user["id"])
                userObj.put("name", user["name"])
                userObj.put("email", user["email"])
                userObj.put("phone", user["phone"])
                userObj.put("createdAt", user["createdAt"])
                jsonArray.put(userObj)
            }
            
            // 将JSON字符串保存到SharedPreferences
            sharedPreferences.edit().putString("users", jsonArray.toString()).apply()
        } catch (e: Exception) {
            Log.e(TAG, "Error saving users", e)
        }
    }

    /**
     * 处理来自Flutter的数据
     * 
     * 当Flutter发送数据到原生时，会调用此方法进行处理
     * 
     * @param data Flutter发送的数据字符串
     */
    private fun handleDataFromFlutter(data: String?) {
        Log.d(TAG, "Received data from Flutter: $data")
        // 处理来自Flutter的数据
        // 可以在这里执行原生功能，如显示Toast、更新UI等
        
        // 示例：显示Toast
        (context as? android.app.Activity)?.runOnUiThread {
            android.widget.Toast.makeText(context, "From Flutter: $data", android.widget.Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 向Flutter发送事件
     * 
     * 用于通知Flutter端数据已更新，触发UI刷新
     * 
     * @param eventType 事件类型，如"userUpdated"
     */
    fun sendEventToFlutter(eventType: String) {
        try {
            val eventData = mapOf("type" to eventType, "timestamp" to System.currentTimeMillis())
            eventSink?.success(eventData)
            Log.d(TAG, "Event sent to Flutter: $eventData")
        } catch (e: Exception) {
            Log.e(TAG, "Error sending event to Flutter", e)
        }
    }
} 